package com.android.duininsuoai.fragment.member;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.duininsuoai.model.member.CouponListDataCallback;
import com.android.duininsuoai.utils.HttpUtils;
import com.android.duininsuoai.utils.MyLog;
import com.android.duininsuoai.utils.ObjectUtils;
import com.android.duininsuoai.view.recycleview.CustomLoadMoreView;
import com.android.duininsuoai.adapt.listMineCouponAdapt;
import com.android.duininsuoai.utils.ConstantsUrl;
import com.android.duininsuoai.R;
import com.android.duininsuoai.model.member.CouponListData;
import com.android.duininsuoai.utils.LoginState;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 *优惠券
 * ---------------------------------------
 */
public class Fragment_Mine_Coupon extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;
    @BindView(R.id.listView)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    private View rootView;

    private static final String ARG_PARAM1 = "param1";

    private String mParam1;


    //控件是否已经初始化
    private boolean isPrepared;
    private listMineCouponAdapt adapter;

    private int page = 1;
    private boolean networkConnected;
    private FragmentActivity mcontext;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);

        }
    }

    public static Fragment_Mine_Coupon newInstance(String param1) {
        Fragment_Mine_Coupon fragment = new Fragment_Mine_Coupon();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);

        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        rootView = inflater.inflate(R.layout.layout_recycle_refresh, container, false);
        ButterKnife.bind(this, rootView);
        mcontext = getActivity();
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        mainTopBg.setVisibility(View.GONE);


        adapter = new listMineCouponAdapt(R.layout.item_list_mine_coupon, null, mParam1);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);

        isPrepared = true;
        setlazyLoad();
        return rootView;
    }


    @Override
    protected void setlazyLoad() {
        super.setlazyLoad();
        if (!isPrepared || !isVisible) {
            return;
        }
        page = 1;
        mRecyclerView.scrollToPosition(0);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            GetDataListData(page, mParam1);
        } else {

            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }

        //刷新
        ReFreshData();


    }

    private void ReFreshData() {
        //设置颜色
        swipeRefreshLayout.setColorSchemeResources(R.color.app_title);

        //自动刷新


        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                networkConnected = ObjectUtils.isNetworkConnected(getActivity());
                if (networkConnected) {

                    page = 1;
                    GetDataListData(page, mParam1);


                } else {

                    ObjectUtils.toast(getActivity(), "无法连接网络");
                    swipeRefreshLayout.setRefreshing(false);
                }


            }
        });


    }


    //获取列表数据
    private void GetDataListData(final int page, String type) {

        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERYOUHUIQUAN + "?&page=" + page + "&type=" + type;


        MyLog.e("地址", address);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String getid = LoginState.getInstance().getid(mcontext);
            String getpd = LoginState.getInstance().getpd(mcontext);
            HashMap<String, String> header = new HashMap<>();

            header.put("UID", getid);
            header.put("UPSW", getpd);
            HttpUtils.get(address, header, null, new CouponListDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    MyLog.e("e", "" + e.toString());
                    swipeRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(CouponListData response, int id) {
                    swipeRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);


                    if (response.getCode() == 0) {
                        ArrayList<CouponListData.Mineyouhuiquandata> listdata = new ArrayList<>();
                        if (response.getData() == null && page == 1) {
                            noData.setVisibility(View.VISIBLE);
                            return;
                        }
                        if (response.getData() != null && response.getData().size() > 0) {
                            listdata.addAll(response.getData());
                            if (page == 1) {
                                adapter.setNewData(listdata);
                            } else {
                                adapter.addData(listdata);
                                adapter.loadMoreComplete();
                            }
                        } else {
                            adapter.loadMoreEnd();
                        }
                    } else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setText(response.getMsg());
                        noDataTv.setVisibility(View.VISIBLE);
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络未连接");
            adapter.loadMoreFail();

        }
    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        page = 1;
        GetDataListData(page, mParam1);

    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetDataListData(page, mParam1);
    }
}
